/*=============================================================================
 Copyright (c) 2005 AUTOMATED LOGIC CORPORATION

 This file is part of DominoTomcatSSOIntegration.
 http://www.automatedlogic.com/domblog.nsf/dx/DominoTomcatSSOIntegration

 DominoTomcatSSOIntegration is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 DominoTomcatSSOIntegration is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 http://www.gnu.org/licenses/gpl.html
 =============================================================================*/

package com.automatedlogic.domino.sso;

import lotus.domino.NotesError;
import lotus.domino.NotesException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LtpaToken cookie stored in the web browser. This may be used to open a DIIOP
 * connection to a Domino server.
 * 
 * @author Brian Green, Automated Logic Corporation
 * @version 2.4.3, Feb 25 2005
 * @since JDK1.4.2_06
 */
public class LtpaToken {

	/**
	 * Interface for reading cookie information in the web browser.
	 */
	public HttpServletRequest request;

	/**
	 * Value of the LtpaToken. This may be used to open a DIIOP connection to
	 * the Domino server. For example: NotesFactory.createSession(dominoServer,
	 * token)
	 */
	private String token;

	/**
	 * If an error occurs, the error message text will be stored here.
	 */
	public String dominoErrorText;

	/**
	 * If an error occurs, the error id will be stored here.
	 */
	public int dominoErrorID;

	/**
	 * The name of the cookie is always "LtpaToken". LTPA is light-weight third
	 * party authentication.
	 */
	public static final String cookieNameLtpaToken = "LtpaToken";

	/**
	 * Create this object with a valid HttpServletRequest object. You may then
	 * reference the "token" property. This is used to get an existing LtpaToken
	 * from the user's cookie.
	 * 
	 * @param request
	 *            HttpServletRequest
	 */
	public LtpaToken(HttpServletRequest request) {
		this.request = request;
		this.token = getCookieValue(cookieNameLtpaToken);
	}

	/**
	 * Create a new LtpaToken. You may then reference "setCookie" to store a new
	 * cookie in user's HttpServletResponse. HttpServletResponse will
	 * automatically store a new LtpaToken cookie in the user's web browser.
	 * 
	 * @param dominoServer
	 *            The host name and port address for connecting to the Domino
	 *            server with DIIOP. Example value: domino.acme.com:63148
	 * @param username
	 *            The user's username.
	 * @param password
	 *            The user's password.
	 */
	public LtpaToken(String dominoServer, String username, String password) {

		//Check for empty username or password.
		if (username.equals("")) {
			dominoErrorID = NotesError.NOTES_ERR_INVALID_USERNAME;
			dominoErrorText = "Invalid user name/password";
			return;
		}
		if (password.equals("")) {
			dominoErrorID = NotesError.NOTES_ERR_INVALID_USERNAME_PASSWD;
			dominoErrorText = "Invalid user name/password";
			return;
		}

		//Open a session with the Domino server.
		DominoBridge dominoBridge = new DominoBridge();
		dominoBridge.openDominoSession(dominoServer, username, password);

		//If a session was opened with the Domino server, then the LtpaToken
		// can be generated.
		if (dominoBridge.isDominoSessionAvailable()) {

			try {
				token = dominoBridge.dominoSession.getSessionToken();
			} catch (NotesException e) {
				throw new RuntimeException(e);
	
			}

			//Close the session with the Domino server.
			dominoBridge.closeDominoSession();

		} else {
			dominoErrorID = dominoBridge.dominoErrorID;
			dominoErrorText = dominoBridge.dominoErrorText;
		}
	}

	/**
	 * Find any cookie value from the browser.
	 * 
	 * @param cookieName
	 *            Name of the cookie.
	 * @return The value of the cookie.
	 */
	private String getCookieValue(String cookieName) {
		Cookie[] cookies = null;

		try {
			cookies = request.getCookies();
			if (cookies != null) {

				for (int iCookieCounter = 0; iCookieCounter < cookies.length; iCookieCounter++) {

					if (cookies[iCookieCounter].getName().toLowerCase().equals(
							cookieName.toLowerCase())) {
						return cookies[iCookieCounter].getValue();
					}
				}
			}
			return null;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * Stores a new LtpaToken in the HttpServletResponse.
	 * 
	 * @param response
	 * @param ltpaTokenCookieDomain
	 * @return true if a cookie was added to the HttpServletResponse, otherwise
	 *         false.
	 */
	public boolean setCookie(HttpServletResponse response,
			String ltpaTokenCookieDomain) {

		if (token == null) {
			return false;
		}

		Cookie cookie = new Cookie(cookieNameLtpaToken, token);
		cookie.setDomain(ltpaTokenCookieDomain);
		cookie.setPath("/");
		response.addCookie(cookie);

		return true;
	}

	/**
	 * @return Text value of the LtpaToken.
	 */
	public String getTokenString() {
		return token;
	}

	/**
	 * @return true if the LtpaToken cookie is valid, otherwise false.
	 */
	public boolean isValid() {

		if (token == null) {
			return false;
		}
		if (token.equals("")) {
			return false;
		}
		return true;

	}

}